package com.elvin.zoe.parser.call;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.elvin.zoe.pojo.Message;
import com.elvin.zoe.util.Configurator;

public class CallLogXmlParser extends CallLogParser {

	private static final String DATE_PATTERN = "EEE, d MMM yyyy HH:mm:ss aaa";

	@Override
	protected List<String> getMessageTokens(String originalHtml) {

		String messageStartToken = "<call";
		String messageEndToken = "/>";
		List<String> messageTokens = new ArrayList<String>();
		int tokenStart = originalHtml.indexOf(messageStartToken);
		
		String[] zoePhoneNumbers = Configurator.zoePhoneNumbers.split(",");
		
		while (tokenStart > 0) {
			int tokenEnd = originalHtml.indexOf(messageEndToken, tokenStart) + messageEndToken.length();
			String messageTag = originalHtml.substring(tokenStart, tokenEnd);
			
			for(String zoeNumber : zoePhoneNumbers){
				if(messageTag.indexOf(zoeNumber) > 0){
					messageTokens.add(messageTag);
					break;
				}
			}
			tokenStart = originalHtml.indexOf(messageStartToken, tokenEnd);
		}
		return messageTokens;
	}

	@Override
	protected int getMessageType(String messageToken) {
		String typeToken = "type=\"2\"";
		if (messageToken.indexOf(typeToken) >= 0) {
			return Message.OUTGOING;
		} else {
			return Message.INCOMMING;
		}
	}

	@Override
	protected String getMessageDatetime(String messageToken) {
        String datetimeStartToken = "date=\"";
        int tokenStart = messageToken.indexOf(datetimeStartToken) + datetimeStartToken.length();
        int tokenEnd = messageToken.indexOf("\"", tokenStart);
        return new SimpleDateFormat(DATE_PATTERN).format(new Date(Long.parseLong(messageToken.substring(tokenStart, tokenEnd))));
	}

	@Override
	protected int getMessageCallDuration(String messageToken) {
        String datetimeStartToken = "duration=\"";
        int tokenStart = messageToken.indexOf(datetimeStartToken) + datetimeStartToken.length();
        int tokenEnd = messageToken.indexOf("\"", tokenStart);
        return Integer.parseInt(messageToken.substring(tokenStart, tokenEnd));
	}

	@Override
	protected String getMessageDatetimeFormat() {
		return DATE_PATTERN;
	}

}
